package com.gree.scmservice.dao;
import com.gree.framework.entity.SaasTenant;
import com.gree.framework.utils.SecurityUtils;
import com.gree.scmservice.config.DataSourceContext;
import com.gree.scmservice.entity.smbse.Smbse06N;
import org.nutz.dao.*;
import org.nutz.dao.entity.Record;
import org.nutz.dao.sql.Sql;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.*;

@Repository
public class MenuDao{
    @Autowired
    private Dao dao;

    public List<Map<String, Object>> selectMenuTreeByUserId(String comp,String temp, Integer fono,Integer styp){
        String clientId = SecurityUtils.getOracleUsername();
        DataSourceContext.setDBType("master");
        SaasTenant saasTenant = dao.fetch(SaasTenant.class, Cnd.where("client_id", "=", clientId));
        String filter = "";
        if (temp.indexOf("ADMINISTRATOR") <= -1) {
            filter = "teno not in (1004) and ";
        }
        String filter_ = "";
        if (!"400".equals(comp)) {
            filter_ = "nvl(sb06.tdsc,'A')<>'S' and ";
        }
        StringBuilder stringBuilder = new StringBuilder("select sb06.*,sb07.fono,sb07.tasc,(select count(*) from smbse07N400 where fono=sb06.teno) sumu from smbse06N400 sb06,");
        if (temp.indexOf("SAASAD") <= -1) {
            stringBuilder.append("(select teno from $smbse08 where ")
                    .append(filter).append("roid in (")
                    .append(temp.substring(0, temp.length() - 1))
                    .append(") group by teno) sb08,");
        }
        stringBuilder
                .append("smbse07N400 sb07 where ").append(filter_)
                .append("(sb06.styp = 0 or sb06.styp = 4) ");
        if (temp.indexOf("SAASAD") <= -1) {
            stringBuilder
                    .append("and sb06.teno=sb08.teno ");
        } else {
            stringBuilder
                    .append("and sb06.teno in (select teno from SAAS_MENU_ADDON t1, SAAS_TENANT_ADDON t2 where t1.addon_id = t2.addon_id and t2.tenant_id = '"+saasTenant.getTenant_id()+"')");
        }
        stringBuilder
                .append("and sb06.teno=sb07.tono ")
                .append("order by sb06.styp desc,sb07.fono,sb07.tasc asc");
        String sqlstr = stringBuilder.toString();

        Sql sql = Sqls.create(sqlstr);

        sql.setVar("smbse08",clientId+".smbse08"+comp).setParam("styp", styp).setParam("fono", fono);

        sql.setCallback(Sqls.callback.entities());
        sql.setEntity(dao.getEntity(Record.class));
        List<Record> record = dao.execute(sql).getList(Record.class);

        return buildMenus(getChildPerms(record, 0));
    }

    public List<Map<String, Object>> buildMenus(List<Map<String, Object>> menus)
    {
        List<Map<String, Object>> routers = new LinkedList<Map<String, Object>>();
        for (Map<String, Object> menu : menus)
        {
            HashMap<String, Object> router = new HashMap<String, Object>();

            router.put("path", feild(menu.get("turl")));
            router.put("styp", feild(menu.get("styp")));
            Map<String, Object> metaMap = new HashMap<String, Object>();
            metaMap.put("title", feild(menu.get("tnam")));
            metaMap.put("icon", feild(menu.get("timg")));
            metaMap.put("teno", feild(menu.get("teno")));
            router.put("meta", metaMap);
            List<Map<String, Object>> cMenus = (List<Map<String, Object>>)menu.get("children");
            if (cMenus != null) {
                if (!cMenus.isEmpty() && cMenus.size() > 0)
                {
                    router.put("children", buildMenus(cMenus));
                }
                else {
                    router.put("children", new ArrayList<>());
                }
            } else {
                router.put("children", new ArrayList<>());
            }

            routers.add(router);
        }
        return routers;
    }

    public List getChildPerms(List<Record> list, int parentId)
    {
        List returnList = new ArrayList();
        for (Iterator iterator = list.iterator(); iterator.hasNext();)
        {
            Record t = (Record) iterator.next();

            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (Integer.valueOf(t.getString("fono")).intValue() == parentId)
            {
                recursionFn(list, t);
                returnList.add(t);
            }
        }
        return returnList;
    }

    private void recursionFn(List<Record> list, Record t)
    {
        // 得到子节点列表
        List<Record> childList = getChildList(list, t);

        t.put("children",childList);

        for (Record tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    private boolean hasChild(List<Record> list, Record t)
    {
        return getChildList(list, t).size() > 0 ? true : false;
    }

    private List<Record> getChildList(List<Record> list, Record t)
    {
        List<Record> tlist = new ArrayList<Record>();
        Iterator<Record> it = list.iterator();
        while (it.hasNext())
        {
            Record n = (Record) it.next();
            if (Long.valueOf(n.getString("fono")).longValue() == Long.valueOf(t.getString("teno")).longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /*public void findMenuTreeByRole(String comp,String temp, Integer fono,Integer styp,List dicList) {
        List<Map<String, Object>> dataDictionaryList = findTenorByRoleAndFono(comp, temp, fono, styp);
        for (Map nav : dataDictionaryList) {
            List<Map<String, Object>> childList = new ArrayList<Map<String, Object>>();
            if (nav != null) {
                Map<String, Object> map = new HashMap<String, Object>();// 每个一级菜单对应的map
                map.put("path", feild(nav.get("turl")));
                Map<String, Object> metaMap = new HashMap<String, Object>();
                metaMap.put("title", feild(nav.get("tnam")));
                metaMap.put("icon", feild(nav.get("timg")));
                metaMap.put("teno", feild(nav.get("teno")));
                map.put("meta", metaMap);
                *//*map.put("teno", feild(nav.get("teno")));*//*
     *//*map.put("sumu", feild(nav.get("sumu")));*//*
     *//*map.put("styp", feild(nav.get("styp")));*//*

                findMenuTreeByRole(comp, temp, Integer.valueOf(nav.get("teno").toString()), styp, childList);
                //将同级代码存入childList中
                map.put("children", childList);
                dicList.add(map);
            }
        }
    }*/

    public List<Record> findMenuByFono(String fono,String filter) {
        String sqlString = "select * from $smbse07 sb07n,$smbse06 sb06n where sb06n.teno = sb07n.tono and sb07n.fono = @fono "+filter+" order by sb07n.tasc, sb07n.tono asc";
        Sql sql = Sqls.create(sqlString);
        sql.setVar("smbse07","smbse07N400")
                .setVar("smbse06","smbse06N400")
                .setParam("fono", fono);
        sql.setCallback(Sqls.callback.entities());
        sql.setEntity(dao.getEntity(Record.class));
        List<Record> list = dao.execute(sql).getList(Record.class);
        return list;
    }

    public Smbse06N fetchSmbse06NByTeno(String comp,Long teno) {
        TableName.set(comp);
        Smbse06N smbse06N= dao.fetch(Smbse06N.class, Cnd.where("teno","=",teno));
        TableName.clear();
        return smbse06N;
    }

    public int updateSmbse06N(String comp,Smbse06N smbse06N) {
        TableName.set(comp);
        int result = dao.update(smbse06N);
        TableName.clear();
        return result;
    }

    public Smbse06N insertSmbse06N(String comp,Smbse06N smbse06N) {
        TableName.set(comp);
        Smbse06N newSmbse06N = dao.insert(smbse06N);
        TableName.clear();
        return newSmbse06N;
    }

    public int deleteSmbse06N(String comp,String teno) {
        TableName.set(comp);
        int result = dao.clear(Smbse06N.class,Cnd.where("teno","=",teno));
        TableName.clear();
        return result;
    }

    public void insertSmbse07N(Long parentId,String menuId,String orderNum) {
        dao.insert("SMBSE07N400", Chain.make("FONO",parentId).add("TONO",menuId).add("TASC",orderNum));
    }

    public int updateSmbse07N(Long parentId,String menuId,String orderNum) {
        int result = dao.update("SMBSE07N400", Chain.make("FONO",parentId).add("TASC",orderNum), Cnd.where("TONO","=",menuId));
        return result;
    }

    public List<Record> querySmbse07NByFono(String fono) {
        List<Record> list = dao.query("SMBSE07N400",Cnd.where("FONO","=",fono));
        return list;
    }

    public int deleteSmbse07N(String menuId) {
        int result = dao.clear("SMBSE07N400",Cnd.where("TONO","=",menuId));
        return result;
    }

    public Record fetchMenuByTeno(String comp,String teno) {
        String sqlString = "select * from $smbse07 sb07n,$smbse06 sb06n where sb06n.teno = sb07n.tono and sb06n.teno = @teno";
        Sql sql = Sqls.create(sqlString);
        sql.setVar("smbse07","smbse07N400")
                .setVar("smbse06","smbse06N400")
                .setParam("teno", teno);
        sql.setCallback(Sqls.callback.entities());
        sql.setEntity(dao.getEntity(Record.class));
        List<Record> list = dao.execute(sql).getList(Record.class);
        return list.get(0);
    }

    public List<Record> querySmbse08ByTeno(String comp,String menuId) {
        List<Record> result = dao.query("SMBSE08"+comp,Cnd.where("TENO","=",menuId));
        return result;
    }

    public List<Record> querySmbse08ByRoid(String comp,String Roid) {
        List<Record> result = dao.query("SMBSE08"+comp,Cnd.where("ROID","=",Roid));
        return result;
    }

    public String feild(Object object) {
        return object==null?"":object.toString();
    }
}
